package com.korion.kdyassistant.utils

import android.accessibilityservice.AccessibilityServiceInfo
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.Settings
import android.view.accessibility.AccessibilityManager
import com.korion.kdyassistant.ui.MainActivity

object PermissionUtils {

    private const val SYSTEM_WINDOW_REQUEST_CODE = 1

    fun checkSystemWindowPermission(activity: Activity): Boolean{
        if (!Settings.canDrawOverlays(activity)){
            val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:${activity.packageName}"))
            activity.startActivityForResult(intent,
                SYSTEM_WINDOW_REQUEST_CODE
            )
            return false
        }
        return true
    }

    fun checkAccessibilityService(activity: Activity): Boolean{
        if (!isAccessibilityServiceEnabled(activity)){
            val intent = Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
            if (intent.resolveActivity(activity.packageManager) != null){
                activity.startActivity(intent)
            } else {
                activity.showToast("系统不支持辅助服务")
            }
            return false
        }
        return true
    }

    fun isAccessibilityServiceEnabled(context: Context): Boolean{
        val service = context.getSystemService(Context.ACCESSIBILITY_SERVICE) as AccessibilityManager
        val list = service.getEnabledAccessibilityServiceList(AccessibilityServiceInfo.FEEDBACK_ALL_MASK)
        list.forEach{
            val serviceInfo = it.resolveInfo.serviceInfo
            //  Log.d(TAG, serviceInfo.packageName)
            if (serviceInfo.packageName == context.packageName){
                return true
            }
        }
        return false
    }

}